import { ImageData } from '@/types/image'
import { Dataset } from '@/types/dataset'
import { Task, TaskResult } from '@/types/task'

// 开发阶段的模拟数据
export const mockImageData: ImageData = {
    id: 'mock-image-1',
    type: '3D',
    format: 'DICOM',
    dimensions: { width: 512, height: 512, depth: 100 },
    pixelSpacing: [1.0, 1.0, 1.0],
    windowCenter: 400,
    windowWidth: 1600,
    pixelData: new ArrayBuffer(512 * 512 * 100 * 2), // 占位数据
    metadata: { patientName: '测试患者', studyDate: '2024-01-01' }
}

export const mockTasks: Task[] = [
    {
        id: 'task-1',
        name: '病灶检测',
        type: 'detection',
        description: '自动检测影像中的病灶区域',
        config: {
            parameters: {
                threshold: 0.5,
                minSize: 10
            }
        },
        status: 'idle',
        datasetId: 'dataset-1',
        createdAt: new Date('2024-01-01'),
        updatedAt: new Date('2024-01-01')
    },
    {
        id: 'task-2',
        name: '病灶分类',
        type: 'classification',
        description: '对检测到的病灶进行分类',
        config: {
            parameters: {
                modelType: 'resnet50',
                classes: ['良性', '恶性']
            }
        },
        status: 'idle',
        datasetId: 'dataset-1',
        createdAt: new Date('2024-01-01'),
        updatedAt: new Date('2024-01-01')
    },
    {
        id: 'task-3',
        name: '器官分割',
        type: 'segmentation',
        description: '分割影像中的器官结构',
        config: {
            parameters: {
                organs: ['肺', '心脏', '肝脏']
            }
        },
        status: 'idle',
        datasetId: 'dataset-1',
        createdAt: new Date('2024-01-01'),
        updatedAt: new Date('2024-01-01')
    }
]

export const mockDatasets: Dataset[] = [
    {
        id: '1',
        name: '胸部CT',
        description: '胸部CT影像数据集，用于肺部疾病检测',
        type: '3D',
        tasks: mockTasks,
        images: [mockImageData],
        imageCount: 1,
        size: 1024 * 1024 * 100, // 100MB
        tags: ['胸部', 'CT', '肺部'],
        isPublic: true,
        owner: 'admin',
        createdAt: new Date('2024-01-01'),
        updatedAt: new Date('2024-01-01')
    },
    {
        id: '2',
        name: '脑部MRI',
        description: '脑部MRI影像数据集，用于脑部疾病诊断',
        type: '3D',
        tasks: mockTasks,
        images: [mockImageData],
        imageCount: 1,
        size: 1024 * 1024 * 80, // 80MB
        tags: ['脑部', 'MRI', '神经'],
        isPublic: true,
        owner: 'admin',
        createdAt: new Date('2024-01-01'),
        updatedAt: new Date('2024-01-01')
    },
    {
        id: '3',
        name: '腹部CT',
        description: '腹部CT影像数据集，用于腹部器官分析',
        type: '3D',
        tasks: mockTasks,
        images: [mockImageData],
        imageCount: 1,
        size: 1024 * 1024 * 120, // 120MB
        tags: ['腹部', 'CT', '器官'],
        isPublic: true,
        owner: 'admin',
        createdAt: new Date('2024-01-01'),
        updatedAt: new Date('2024-01-01')
    },
    {
        id: '4',
        name: '心脏超声',
        description: '心脏超声影像数据集，用于心脏功能评估',
        type: '2D',
        tasks: mockTasks,
        images: [mockImageData],
        imageCount: 1,
        size: 1024 * 1024 * 25, // 25MB
        tags: ['心脏', '超声', '功能'],
        isPublic: true,
        owner: 'admin',
        createdAt: new Date('2024-01-01'),
        updatedAt: new Date('2024-01-01')
    },
    {
        id: '5',
        name: '乳腺X光',
        description: '乳腺X光影像数据集，用于乳腺癌筛查',
        type: '2D',
        tasks: mockTasks,
        images: [mockImageData],
        imageCount: 1,
        size: 1024 * 1024 * 15, // 15MB
        tags: ['乳腺', 'X光', '筛查'],
        isPublic: true,
        owner: 'admin',
        createdAt: new Date('2024-01-01'),
        updatedAt: new Date('2024-01-01')
    }
]
/**
 
* Generate mock datasets
 */
export function generateMockDatasets(count: number): Dataset[] {
    const datasets: Dataset[] = []

    for (let i = 0; i < count; i++) {
        const id = `dataset-${i + 1}`
        const names = ['胸部CT', '脑部MRI', '腹部CT', '心脏超声', '乳腺X光', '骨骼X光', '肾脏CT']
        const types: ('2D' | '3D')[] = ['2D', '3D']

        const dataset: Dataset = {
            id,
            name: names[i % names.length] || `数据集 ${i + 1}`,
            description: `数据集 ${i + 1} 的描述信息`,
            type: types[i % types.length],
            tasks: generateMockTasks(Math.floor(Math.random() * 3) + 1),
            images: [generateMockImageData(`image-${i + 1}`, types[i % types.length])],
            imageCount: Math.floor(Math.random() * 100) + 1,
            size: Math.floor(Math.random() * 1000000000) + 1000000, // 1MB to 1GB
            tags: ['标签1', '标签2'],
            isPublic: Math.random() > 0.5,
            owner: 'admin',
            createdAt: new Date(Date.now() - Math.random() * 365 * 24 * 60 * 60 * 1000),
            updatedAt: new Date()
        }

        datasets.push(dataset)
    }

    return datasets
}

/**
 * Generate mock image data
 */
export function generateMockImageData(id: string, type: '2D' | '3D'): ImageData {
    const width = Math.floor(Math.random() * 1024) + 256
    const height = Math.floor(Math.random() * 1024) + 256
    const depth = type === '3D' ? Math.floor(Math.random() * 200) + 50 : undefined

    const dimensions = type === '3D'
        ? { width, height, depth: depth! }
        : { width, height }

    const pixelDataSize = type === '3D'
        ? width * height * depth! * 2
        : width * height * 2

    return {
        id,
        type,
        format: 'DICOM',
        dimensions,
        pixelSpacing: [1.0, 1.0, 1.0],
        windowCenter: Math.floor(Math.random() * 1000) + 100,
        windowWidth: Math.floor(Math.random() * 2000) + 500,
        pixelData: new ArrayBuffer(pixelDataSize),
        metadata: {
            patientName: `患者 ${id}`,
            studyDate: new Date().toISOString().split('T')[0]
        }
    }
}

/**
 * Generate mock tasks
 */
export function generateMockTasks(count: number): Task[] {
    const tasks: Task[] = []
    const taskTypes: Task['type'][] = ['detection', 'classification', 'segmentation']
    const taskNames = ['病灶检测', '病灶分类', '器官分割', '图像增强', '质量评估']
    const statuses: Task['status'][] = ['idle', 'running', 'completed', 'error']

    for (let i = 0; i < count; i++) {
        const type = taskTypes[i % taskTypes.length]
        const task: Task = {
            id: `task-${i + 1}`,
            name: taskNames[i % taskNames.length] || `任务 ${i + 1}`,
            type,
            description: `${taskNames[i % taskNames.length]} 的详细描述`,
            config: {
                parameters: {
                    threshold: Math.random(),
                    modelType: 'default',
                    ...(type === 'detection' && { minSize: Math.floor(Math.random() * 20) + 5 }),
                    ...(type === 'classification' && { classes: ['类别1', '类别2', '类别3'] }),
                    ...(type === 'segmentation' && { organs: ['器官1', '器官2'] })
                }
            },
            status: statuses[Math.floor(Math.random() * statuses.length)],
            datasetId: 'dataset-1',
            createdAt: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000),
            updatedAt: new Date()
        }

        tasks.push(task)
    }

    return tasks
}

/**
 * Generate mock task results
 */
export function generateMockTaskResults(taskId: string, taskType: Task['type']): any {
    const results: any[] = []
    const resultCount = Math.floor(Math.random() * 5) + 1

    for (let i = 0; i < resultCount; i++) {
        switch (taskType) {
            case 'detection':
                results.push({
                    type: 'detection',
                    confidence: Math.random(),
                    boundingBox: {
                        x: Math.floor(Math.random() * 400),
                        y: Math.floor(Math.random() * 400),
                        width: Math.floor(Math.random() * 100) + 20,
                        height: Math.floor(Math.random() * 100) + 20
                    },
                    label: `检测结果 ${i + 1}`
                })
                break

            case 'classification':
                results.push({
                    type: 'classification',
                    confidence: Math.random(),
                    label: `类别 ${i + 1}`,
                    probability: Math.random()
                })
                break

            case 'segmentation':
                const width = Math.floor(Math.random() * 200) + 100
                const height = Math.floor(Math.random() * 200) + 100
                results.push({
                    type: 'segmentation',
                    confidence: Math.random(),
                    mask: {
                        width,
                        height,
                        data: new ArrayBuffer(width * height)
                    },
                    label: `分割区域 ${i + 1}`
                })
                break
        }
    }

    const metrics: Record<string, number> = {
        accuracy: Math.random()
    }

    // Add task-specific metrics
    if (taskType === 'detection') {
        metrics.precision = Math.random()
        metrics.recall = Math.random()
        metrics.f1Score = Math.random()
    } else if (taskType === 'segmentation') {
        metrics.iou = Math.random()
        metrics.dice = Math.random()
    }

    return {
        taskId,
        status: Math.random() > 0.1 ? 'completed' : 'error',
        results,
        metrics,
        executionTime: Math.floor(Math.random() * 30000) + 1000, // 1-30 seconds
        timestamp: new Date(),
        ...(Math.random() > 0.8 && {
            error: {
                message: '处理过程中出现错误',
                code: 'PROCESSING_ERROR'
            }
        })
    }
}